﻿namespace zijian666.Data;

public class DbDiagnosticInterceptor : IDbInterceptor
{
    public static DbDiagnosticInterceptor Instance { get; } = new DbDiagnosticInterceptor();

    public ValueTask CommandCreated(DbCommandCreatedInterceptorContext context)
    {
        var cmd = context.Command;
        Diagnostic.Wirte("SQL", cmd.CommandText);
        Diagnostic.Wirte("SQLParams", string.Join("; ", cmd.Parameters.Cast<IDataParameter>().Select(x => $"{x.ParameterName}: {x.Value}({x.DbType})")));
        return ValueTask.CompletedTask;
    }

    public ValueTask QueryStarting(DbExecuteReaderInterceptorContext context)
    {
        Diagnostic.Wirte("QueryStarting", context.Elapsed.TotalMilliseconds + " ms");
        return ValueTask.CompletedTask;
    }

    public ValueTask QueryExecuted(DbExecuteReaderInterceptorContext context)
    {
        Diagnostic.Wirte("QueryExecuted", context.Elapsed.TotalMilliseconds + " ms");
        return ValueTask.CompletedTask;
    }

    public ValueTask NonQueryExecuted(DbExecuteNonQueryInterceptorContext context)
    {
        Diagnostic.Wirte("NonQueryExecuted", context.Elapsed.TotalMilliseconds + " ms");
        return ValueTask.CompletedTask;
    }

    public ValueTask TransactionStarting(DbTransactionInterceptorContext context)
    {
        Diagnostic.Wirte("Transaction", "Begin");
        return ValueTask.CompletedTask;
    }

    public ValueTask TransactionCommitted(DbTransactionInterceptorContext context)
    {
        Diagnostic.Wirte("Transaction", "Commit");
        return ValueTask.CompletedTask;
    }
    public ValueTask TransactionRollbacked(DbTransactionInterceptorContext context)
    {
        Diagnostic.Wirte("Transaction", "Rollback");
        return ValueTask.CompletedTask;
    }

    public ValueTask ConnectionStateChanging(DbConnectionInterceptorContext context)
    {
        Diagnostic.Wirte("Connect", $"State: {context.OriginalState} -> {context.NewState}");
        return ValueTask.CompletedTask;
    }

    public ValueTask ExceptionOccurred(DbExceptionContext context)
    {
        Diagnostic.Error(context.Exception, context.File, context.Member, context.Line);
        return ValueTask.CompletedTask;
    }

    public ValueTask EntityInserting(DbEntityInterceptorContext context) => ValueTask.CompletedTask;

    public ValueTask EntityUpdateing(DbEntityInterceptorContext context) => ValueTask.CompletedTask;

    public ValueTask EntityDeleting(DbEntityInterceptorContext context) => ValueTask.CompletedTask;

    public ValueTask EntityInserted(DbEntityInterceptorContext context) => ValueTask.CompletedTask;

    public ValueTask EntityUpdated(DbEntityInterceptorContext context) => ValueTask.CompletedTask;

    public ValueTask EntityDeleted(DbEntityInterceptorContext context) => ValueTask.CompletedTask;
}